package com.xing.controller;

import com.xing.exception.SystemException;
import com.xing.pojo.Book;
import com.xing.service.BookService;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,flag);

    }
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    @GetMapping("/{id}")
    public Result getBookById(@PathVariable(value = "id") Integer id) {
        Book book = bookService.getBookById(id);
        Integer code;
        String msg;

        //模拟异常

//        if (id == 1){
//            throw new SystemException(Code.System_ERR,"系统错误");
//        }
//        try{
//            int i = 1/0;
//        }catch (Exception e){
//            throw new SystemException(Code.System_ERR,"系统错误");
//        }
        if (book != null){
            code = Code.GET_OK;
            msg = "";
        }else {
            code = Code.GET_ERR;
            msg = "数据查询失败，请重试！";
        }
        return new Result(code,book,msg);
    }
    @GetMapping
    public Result getBookList() {
        List<Book> bookList = bookService.getBookList();
        Integer code;
        String msg;
        if (bookList != null){
            code = Code.GET_OK;
            msg = "";
        }else {
            code = Code.GET_ERR;
            msg = "数据查询失败，请重试！";
        }
        return new Result(code,bookList,msg);
    }
}
